<?php
/**
 * Created by PhpStorm.
 * User: zrc
 * Date: 2018/05/05
 * Time: 下午 4:16
 * desc 验证用户token
 */

namespace App\Http\Middleware;

use Closure;
use App\Models\User;


class CheckToken
{
    /**
     * @author zrc
     * @date 2018/05/05
     * @param $request
     * @param Closure $next
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|mixed
     */
    public function handle($request, Closure $next)
    {
        $info = $request->all();
//        $api_controller = ['LoginController'];
//        $controller = get_class($request->route()->getController());
//        $controllerArr = explode('\\',$controller);
//        $controllerName = array_pop($controllerArr);
        if (!empty($info['uid'])){
            $user_check = User::where('id',$info['uid'])->first();
            if (empty($info['token'])||!$user_check) {
//                if (in_array($controllerName,$api_controller)){
//                    return respF(3025);
//                }
                //用户ID不正确
                return respF(3025);

                //return redirect('api/error');

            }
//            dump($user_check);die;
            if ($user_check->token!=$info['token']){
                //token 不正确
//                if (in_array($controllerName,$api_controller)){
//                    return respF(3024);
//                }
                //return redirect('api/login/error');
                return respF(3024);
            }
            $mid_params = ['token'=>$user_check->token];
            $request->merge($mid_params);//合并参数
            return $next($request);
        }
        return $next($request);
    }

}